const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
// 创建集合云函数入口函数
exports.main = async (event, context) => {
  try {
    console.log(event)
    let groupMaxNum = []
    let personMaxNum = []
    let genderMaxNum = []
    let count = await db.collection('student').where({ class: 5 }).count()
    let male = await db.collection('student').where({ class: 5,gender:'男' }).count()
    let female = await db.collection('student').where({ class: 5 ,gender:'女'}).count()
    let groups = await db.collection('student').aggregate()
      .group({
        _id: '$group',
      })
      .end()
    groups = groups.list
    console.log(groups)

    let group_max = 10
    for (const it of groups) {
      let temp = await db.collection('student').where({ group: it._id }).count()
      group_max = group_max < temp.total ? group_max : temp.total
    }
    for (let index = 0; index < group_max; index++) {
      groupMaxNum[index] = index + 1
    }
    let genderIndex = male.total < female.total ? male.total : female.total
    for (let index = 0; index < genderIndex; index++) {
      genderMaxNum[index] = index + 1
    }
    for (let index = 0; index < count.total; index++) {
      personMaxNum[index] = index + 1
    }
    return {
      success: true,
      data: {
        groupMaxNum: groupMaxNum,
        personMaxNum: personMaxNum,
        genderMaxNum: genderMaxNum
      }
    }

  } catch (e) {
    return {
      success: false,
      data: e
    }
  }
}